<template>
  <!-- 加载状态 -->
  <LoadingSpinner v-if="isInitialLoading" />

  <!-- 主要内容 -->
  <PageLayout 
    v-else
    title="分类浏览" 
    description="按类型、地区、年份等条件筛选电影"
  >
    <!-- 使用通用筛选器组件 -->
    <div class="relative z-30">
      <MovieFilterList
        :movies="displayMovies"
        :is-loading="isLoading"
        :has-more="hasMore"
        :initial-filters="filters"
        :initial-sort="currentSort"
        :sort-options="sortOptions"
        :empty-state-title="hasActiveFilters ? '暂无符合条件的电影' : '暂无电影数据'"
        :empty-state-description="hasActiveFilters ? '请尝试调整筛选条件' : '请稍后再试'"
        @update:filters="handleFiltersUpdate"
        @update:sort="handleSortUpdate"
        @load-more="loadMore"
        @clear-filters="clearFilters"
      />
    </div>
  </PageLayout>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, watch } from 'vue'
import { useMovieLoader } from '../composables/movies'
import { MovieFilterList } from '../components/movie'
import { LoadingSpinner } from '../components/ui'
import PageLayout from '../components/layout/PageLayout.vue'

const { loadMovies, isLoading, hasMore } = useMovieLoader()

// 响应式数据
const isInitialLoading = ref(true)
const movies = ref<any[]>([])
const currentPage = ref(0)
const pageSize = 20

// 排序选项
const sortOptions = [
  { key: 'views', label: '播放量', icon: '👁️' },
  { key: 'updated_at', label: '最新更新', icon: '🕒' },
  { key: 'year', label: '上映年份', icon: '📅' },
  { key: 'rating', label: '评分最高', icon: '⭐' }
]

const currentSort = ref('views')

// 筛选状态
const filters = ref({
  genre: 'all',
  universe: 'all',
  language: 'all',
  country: 'all',
  ai: 'all'
})

// 计算属性
const hasActiveFilters = computed(() => {
  return filters.value.genre !== 'all' || 
         filters.value.universe !== 'all' || 
         filters.value.language !== 'all' || 
         filters.value.country !== 'all' || 
         filters.value.ai !== 'all'
})

// 客户端筛选和排序
const filteredAndSortedMovies = computed(() => {
  let filtered = [...movies.value]

  // 应用筛选条件
  if (filters.value.genre !== 'all') {
    filtered = filtered.filter(movie => 
      movie.genres && movie.genres.includes(filters.value.genre)
    )
  }

  if (filters.value.universe !== 'all') {
    filtered = filtered.filter(movie => {
      if (Array.isArray(movie.universe)) {
        return movie.universe.includes(filters.value.universe)
      }
      return movie.universe === filters.value.universe
    })
  }

  if (filters.value.language !== 'all') {
    filtered = filtered.filter(movie => {
      if (Array.isArray(movie.language)) {
        return movie.language.includes(filters.value.language)
      }
      return movie.language === filters.value.language
    })
  }

  if (filters.value.country !== 'all') {
    filtered = filtered.filter(movie => {
      if (Array.isArray(movie.country)) {
        return movie.country.includes(filters.value.country)
      }
      return movie.country === filters.value.country
    })
  }

  if (filters.value.ai !== 'all') {
    const isAi = filters.value.ai === 'ai'
    filtered = filtered.filter(movie => movie.isAi === isAi)
  }

  // 应用排序
  filtered.sort((a, b) => {
    let result = 0
    switch (currentSort.value) {
      case 'views':
        result = (b.views || 0) - (a.views || 0)
        break
      case 'rating':
        result = (b.rating || 0) - (a.rating || 0)
        break
      case 'year':
        result = (b.year || 0) - (a.year || 0)
        break
      case 'updated_at':
        result = new Date(b.updatedAt || 0).getTime() - new Date(a.updatedAt || 0).getTime()
        break
      default:
        result = 0
    }
    return result
  })

  return filtered
})

const displayMovies = computed(() => {
  return filteredAndSortedMovies.value.slice(0, (currentPage.value + 1) * pageSize)
})

// 方法
const handleFiltersUpdate = (newFilters: Record<string, string>) => {
  filters.value = {
    genre: newFilters.genre || 'all',
    universe: newFilters.universe || 'all',
    language: newFilters.language || 'all',
    country: newFilters.country || 'all',
    ai: newFilters.ai || 'all'
  }
  // 重置分页，但不重新加载数据
  currentPage.value = 0
}

const handleSortUpdate = (newSort: string) => {
  currentSort.value = newSort
  // 排序变化不需要重新加载数据，只需要重新排序
}

const clearFilters = () => {
  filters.value = {
    genre: 'all',
    universe: 'all',
    language: 'all',
    country: 'all',
    ai: 'all'
  }
  // 重置分页，但不重新加载数据
  currentPage.value = 0
}

const loadMoviesByFilters = async () => {
  isInitialLoading.value = true
  currentPage.value = 0
  try {
    // 重置加载状态
    hasMore.value = true
    // 加载更多数据以支持客户端筛选
    const allMovies = await loadMovies(500, 'category', 0, {
      genre: 'all',
      universe: 'all',
      language: 'all',
      country: 'all',
      ai: 'all'
    })
    movies.value = allMovies
    
    // 检查是否还有更多数据
    hasMore.value = allMovies.length === 500
  } catch (error) {
    console.error('Error loading movies by filters:', error)
    movies.value = []
    hasMore.value = false
  } finally {
    isInitialLoading.value = false
  }
}

const loadMore = async () => {
  if (isLoading.value || !hasMore.value) return
  
  try {
    isLoading.value = true
    currentPage.value++
    
    // 客户端分页，不需要重新加载数据
    // 如果当前显示的电影数量接近总数，可以考虑加载更多
    if (displayMovies.value.length >= movies.value.length - pageSize) {
      const newMovies = await loadMovies(pageSize, 'category', movies.value.length, {
        genre: 'all',
        universe: 'all',
        language: 'all',
        country: 'all',
        ai: 'all'
      })
      
      if (newMovies.length > 0) {
        movies.value.push(...newMovies)
        // 检查是否还有更多数据
        hasMore.value = newMovies.length === pageSize
      } else {
        hasMore.value = false
      }
    }
  } catch (error) {
    console.error('Error loading more movies:', error)
    hasMore.value = false
  } finally {
    isLoading.value = false
  }
}

// 监听筛选变化 - 移除这个监听器，因为现在使用客户端筛选
// watch([filters], () => {
//   loadMoviesByFilters()
// }, { deep: true })

onMounted(() => {
  loadMoviesByFilters()
})
</script> 